home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C08 / Quoter.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.3 KB  |  55 lines

  1. //: C08:Quoter.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Random quote selection
  7. #include <iostream>
  8. #include <cstdlib> // Random number generator
  9. #include <ctime> // To seed random generator
  10. using namespace std;
  11.  
  12. class Quoter {
  13.   int lastquote;
  14. public:
  15.   Quoter();
  16.   int lastQuote() const;
  17.   const char* quote();
  18. };
  19.  
  20. Quoter::Quoter(){
  21.   lastquote = -1;
  22.   srand(time(0)); // Seed random number generator
  23. }
  24.  
  25. int Quoter::lastQuote() const {
  26.   return lastquote;
  27. }
  28.  
  29. const char* Quoter::quote() {
  30.   static const char* quotes[] = {
  31.     "Are we having fun yet?",
  32.     "Doctors always know best",
  33.     "Is it ... Atomic?",
  34.     "Fear is obscene",
  35.     "There is no scientific evidence "
  36.     "to support the idea "
  37.     "that life is serious",
  38.     "Things that make us happy, make us wise",
  39.   };
  40.   const int qsize = sizeof quotes/sizeof *quotes;
  41.   int qnum = rand() % qsize;
  42.   while(lastquote >= 0 && qnum == lastquote)
  43.     qnum = rand() % qsize;
  44.   return quotes[lastquote = qnum];
  45. }
  46.  
  47. int main() {
  48.   Quoter q;
  49.   const Quoter cq;
  50.   cq.lastQuote(); // OK
  51. //!  cq.quote(); // Not OK; non const function
  52.   for(int i = 0; i < 20; i++)
  53.     cout << q.quote() << endl;
  54. } ///:~
  55.